package com.yindian.cos.monitor.filter;

import com.yindian.cos.monitor.core.TrackerService;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求过滤器，过滤所有请求，记录请求链的调用
 *
 * @author zhangchuanhao
 * @create 2018/11/5 10:55
 */
@Log4j2
public class LogFilter extends OncePerRequestFilter {

    private final TrackerService trackerService;

    public LogFilter(TrackerService trackerService) {
        this.trackerService = trackerService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        trackerService.trackerStart(request);
        request.setAttribute(TrackerService.TRACKER_ID, TrackerService.getTrackerId());
        log.debug("进入LogFilter，method = {},url = {}", request.getMethod(), request.getRequestURL());
        filterChain.doFilter(request, response);
        Integer statusCode = response.getStatus();
        if (HttpStatus.NOT_FOUND.value() == statusCode) {
            log.error("未找到当前路径,url = {}", request.getRequestURL());
        }
        log.debug("销毁当前tracker信息，method = {},url = {}", request.getMethod(), request.getRequestURL());
        TrackerService.trackerEnd();
    }
}
